#pragma once

#include "Math/Math.h"
#include <vector>
#include "Math/Ray.h"


struct Triangle
{
	glm::vec3 p1, p2, p3;
	glm::vec3 center;
	Triangle(glm::vec3 a, glm::vec3 b, glm::vec3 c)
	{
		p1 = a, p2 = b, p3 = c;
		center = (p1 + p2 + p3) / glm::vec3(3.f);
	}
};

struct BVHNode
{
	BVHNode* left;
	BVHNode* right;
	int32 n; // Triangle Num
	int32 l; // Left index
	glm::vec3 aa, bb;

	BVHNode()
	{
		left = nullptr;
		right = nullptr;
		n = 0;
		l = 0;
		aa = glm::vec3(FLT_MAX);
		bb = glm::vec3(-FLT_MAX);
	}
};

struct HitResult {

	float distance;
	BVHNode* node;
	Triangle* triangle;

	HitResult()
	{
		distance = FLT_MAX;
		triangle = nullptr;
		node = nullptr;
	}
};

float HitTriangle(Triangle* triangle, Ray ray);

BVHNode* BuildBVH(std::vector<Triangle>& triangles, int l, int r, int n);

BVHNode* BuildBVHWithSAH(std::vector<Triangle>& triangles, int l, int r, int n);

void FreeBvh(BVHNode* node);

bool IsHitNode(Ray& ray, BVHNode* node);

HitResult HitNodeResult(std::vector<Triangle>& triangles, Ray& ray, BVHNode* node);





